package com.zxblog.controller;

import com.zxblog.domain.UserAdmin;
import com.zxblog.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/admin")
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object loginAdmin(@RequestBody Map<String,Object> requestBody, HttpServletRequest request){
        Map<String,Object> retMap = new LinkedHashMap<>();

        String userName = (String) requestBody.get("userName");
        String password = (String) requestBody.get("password");
        if (Objects.equals(userName, "") && Objects.equals(password, "")) { // 效验用户输入数据完整性
            retMap.put("code",400);
            retMap.put("msg","请求参数不完整");
            retMap.put("requiredParameter",new String[]{"userName","password"});
            return retMap;
        }
        // 完整性验证成功
        UserAdmin userAdmin = adminUserService.loginUser(userName, password);
        if (userAdmin != null){
            retMap.put("code",200);
            retMap.put("msg","用户登录成功");
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(3 * 24 * 60 * 60); // day * hours * min * sec
            session.setAttribute("admin",userAdmin);
        } else {
            retMap.put("code",500);
            retMap.put("msg","用户名密码错误,或服务器异常。");
        }
        return retMap;
    }
}
